package com.bears.god.sup.servlet.operation;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bears.god.sup.model.Vendor;
import com.bears.god.sup.service.IVendorService;
import com.bears.god.sup.service.ServiceDAOFactory;

@WebServlet("/addVendor.do")
public class AddVendorServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 3121L;
	
	public static final String METHOD_FINISH = "0";
	public static final String METHOD_ADD = "1";
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding("UTF-8");
		String method = req.getParameter("method");
		
		if(method != null)
		{
			switch(method){
			 case AddVendorServlet.METHOD_FINISH:
				 finish(req,resp);
				 break;
			 case AddVendorServlet.METHOD_ADD:
				 add(req,resp);
				 break;
			}
			
		}
	}

	private void add(HttpServletRequest req, HttpServletResponse resp) {
		try {
			req.getRequestDispatcher("WEB-INF/view/cashier/addvendor.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
	}

	private void finish(HttpServletRequest req, HttpServletResponse resp) {
		Vendor vendor = new Vendor();
		
		try{
			String vendorName = req.getParameter("vendor_name");
			String vendorAddr = req.getParameter("vendor_addr");
			String vendorPhone = req.getParameter("vendor_phone");
			String vendorFAX = req.getParameter("vendor_FAX");
			String contactPerson = req.getParameter("contact_person");
			
			vendor.setVendor(vendorName);
			vendor.setVendorAddress(vendorAddr);
			vendor.setVendorPhone(vendorPhone);
			vendor.setVendorFAX(vendorFAX);
			vendor.setContactPerson(contactPerson);
			
			
			IVendorService service = ServiceDAOFactory.getVendorDAO();
			service.save(vendor);
			
			req.setAttribute("AddVendor_success", "添加成功");
			//System.out.println("成功"+deptName);
			req.getRequestDispatcher("/Vendor").forward(req, resp);
		}catch (Exception e) {
			e.printStackTrace();
			try {
				req.setAttribute("AddVendor_err", "添加失败");
				req.getRequestDispatcher("WEB-INF/view/cashier/addvendor.jsp").forward(req, resp);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
	}
	}
}
